import { login, logout, refreshToken } from '@/api/auth'
import { Key, PcCookie } from '@/utils/cookie'


const state = {
    userInfo: PcCookie.get(Key.userInfoKey) ? JSON.parse(PcCookie.get(Key.userInfoKey)) : null,
    accessToken: PcCookie.get(Key.accessTokenKey),
    refreshToken: PcCookie.get(Key.refreshTokenKey),
}

const actions = {
    // 登录操作
    UserLogin({ commit }, userInfo) {
        const { username, password } = userInfo

        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password }).then(response => {
                const { code, data } = response
                if (code === 20000) {
                    commit('SET_USER_STATE', data)
                }

                resolve(response)
            }).catch(error => {
                console.log(error);
                commit('RESET_USER_STATE')
                reject(error)

            })
        })
    },

    // 退出
    UserLogout({ commit, state }, redirectURL) {
        logout(state.accessToken).then(response => {
            // 重置用户状态
            commit('RESET_USER_STATE')
            // 退出后，重写向地址，如果没有传重写向到登录页
            window.location.href = redirectURL || '/'
        }).catch(error => {
            commit('RESET_USER_STATE')
            window.location.href = redirectURL || '/'
        })
    },
    // 发送刷新令牌
    SendRefreshToken({ commit, state }) {
        return new Promise((resolve, reject) => {

            if (!state.refreshToken) {
                commit('RESET_USER_STATE')
                reject('没有刷新令牌')
                return
            }

            refreshToken(state.refreshToken).then(response => {
                if (response.code === 20000) {
                    commit('SET_USER_STATE', response.data)
                    resolve()
                } else {
                    reject(response.message)
                }


            }).catch(error => {
                commit('RESET_USER_STATE')

                reject(error)
            })
        })


    }

}

const mutations = {
    // 赋值用户状态
    SET_USER_STATE(state, data) {
        const { userInfo, access_token, refresh_token } = data
        state.userInfo = userInfo
        state.accessToken = access_token
        state.refreshToken = refresh_token
        PcCookie.set(Key.userInfoKey, JSON.stringify(userInfo))
        PcCookie.set(Key.accessTokenKey, access_token)
        PcCookie.set(Key.refreshTokenKey, refresh_token)
    },

    // 重置用户状态,退出和登录失败时用
    RESET_USER_STATE(state) {
        state.userInfo = null
        state.accessToken = null
        state.refreshToken = null
        PcCookie.remove(Key.userInfoKey)
        PcCookie.remove(Key.accessTokenKey)
        PcCookie.remove(Key.refreshTokenKey)

    }
}

export default {
    state,
    mutations,
    actions
}